// pages/mymassage/mymassage.js
let db = wx.cloud.database()
let subject = db.collection("subject")
Page({
    data: {
      topicArray: [],
    },
    setHotTopic(event) {
      // 获取自定义属性
      let id = event.currentTarget.dataset.id;
      let switch1Checked = event.detail.value;
      // console.log(switch1Checked);
      subject.where({
          _id: id
        }).update({
          data: {
            hot: switch1Checked
          }
        })
        .then(
          res => {
            // console.log(res)
            if(res.errMsg == "collection.update:ok"){
               wx.showToast({
                 icon:"none",
                 title: '设置成功',
               })
            }
          }
        )
    },
    // 管理题目 cms
    // 获取所有题目数据
    getTopicData() {
      wx.showLoading({
        title: '加载中',
      })
      this.setData({
        topicArray: []
      })
      let that = this;
      subject.count()
        .then(
          async res => {
            // console.log(res);
            let total = res.total; 
            let len = Math.ceil(total / 20); 
            for (let i = 0; i < len; i++) { 
              await subject.skip(i * 20).limit(20)
                .get()
                .then(
                  async res => {
                    let new_data = res.data;
                    let old_data = that.data.topicArray;
                    that.setData({
                      topicArray: old_data.concat(new_data)
                    })
                    if(that.data.topicArray.length == total){
                      wx.hideLoading();
                    }
                  }
                )
            }
  
            // console.log(this.data.topicArray);
          }
        )
    },
    getTopicData2022() {
      topicTable.get()
        .then(
          res => {
            // console.log(res);
            if (res.errMsg == "collection.get:ok") {
              this.setData({
                topicArray: res.data
              })
            }
          }
        )
    },
    // 删除指定的题目
    removeTopic(event) {
      let that = this;
      wx.showModal({
        title: '是否删除？',
        success(){
          // 获取自定义属性
          let id = event.currentTarget.dataset.id;
          let _openid = "ok0365GOM91dlJNNMnRMwBzzAxwc";
          subject.where({
            _id: id,
            _openid: _openid
          }).remove().then(
            res => {
              // console.log(res);
              if (res.errMsg == "collection.remove:ok") {
                wx.showToast({
                  title: '删除成功',
                })
                let timeout = setTimeout(() => {
                  that.getTopicData();
                }, 600);
              }
            }
          )
        }
      })
      
    },
    onLoad: function () {
      this.getTopicData()
    }
  })